import React, { useEffect, useState } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  DatePicker,
  Select,
  Space,
  Button,
  Table,
  Typography,
  Progress,
  Tag,
} from 'antd';
import {
  DollarOutlined,
  ShoppingCartOutlined,
  UserOutlined,
  TrendingUpOutlined,
  DownloadOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import * as echarts from 'echarts';
import { useAppDispatch } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
const { Option } = Select;

interface StatisticsData {
  totalOrders: number;
  totalRevenue: number;
  totalCustomers: number;
  avgOrderValue: number;
  orderTrend: Array<{ date: string; orders: number; revenue: number }>;
  statusDistribution: Array<{ status: string; count: number; percentage: number }>;
  topProducts: Array<{ name: string; sales: number; revenue: number }>;
  topCustomers: Array<{ name: string; orders: number; revenue: number }>;
}

const OrderStatistics: React.FC = () => {
  const dispatch = useAppDispatch();
  
  const [loading, setLoading] = useState(false);
  const [dateRange, setDateRange] = useState<[string, string] | null>(null);
  const [statistics, setStatistics] = useState<StatisticsData | null>(null);

  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '订单管理' },
      { title: '订单统计' },
    ]));
  }, [dispatch]);

  useEffect(() => {
    loadStatistics();
  }, [dateRange]);

  // 加载统计数据
  const loadStatistics = async () => {
    try {
      setLoading(true);
      
      // 模拟统计数据
      const mockStatistics: StatisticsData = {
        totalOrders: 1250,
        totalRevenue: 2580000,
        totalCustomers: 850,
        avgOrderValue: 2064,
        orderTrend: [
          { date: '2024-01-01', orders: 45, revenue: 89000 },
          { date: '2024-01-02', orders: 52, revenue: 105000 },
          { date: '2024-01-03', orders: 38, revenue: 76000 },
          { date: '2024-01-04', orders: 61, revenue: 125000 },
          { date: '2024-01-05', orders: 48, revenue: 98000 },
          { date: '2024-01-06', orders: 55, revenue: 112000 },
          { date: '2024-01-07', orders: 42, revenue: 85000 },
        ],
        statusDistribution: [
          { status: 'delivered', count: 850, percentage: 68 },
          { status: 'shipped', count: 150, percentage: 12 },
          { status: 'paid', count: 125, percentage: 10 },
          { status: 'pending', count: 75, percentage: 6 },
          { status: 'cancelled', count: 50, percentage: 4 },
        ],
        topProducts: [
          { name: 'iPhone 15 Pro Max', sales: 120, revenue: 1200000 },
          { name: 'MacBook Pro 16', sales: 80, revenue: 1600000 },
          { name: 'AirPods Pro', sales: 200, revenue: 400000 },
          { name: '小米14 Pro', sales: 150, revenue: 750000 },
          { name: 'iPad Air', sales: 90, revenue: 450000 },
        ],
        topCustomers: [
          { name: '张三', orders: 15, revenue: 150000 },
          { name: '李四', orders: 12, revenue: 120000 },
          { name: '王五', orders: 10, revenue: 200000 },
          { name: '赵六', orders: 8, revenue: 80000 },
          { name: '钱七', orders: 7, revenue: 140000 },
        ],
      };
      
      setStatistics(mockStatistics);
      
      // 渲染图表
      setTimeout(() => {
        renderCharts(mockStatistics);
      }, 100);
      
    } catch (error) {
      console.error('加载统计数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 渲染图表
  const renderCharts = (data: StatisticsData) => {
    // 订单趋势图
    const trendChart = echarts.init(document.getElementById('trend-chart'));
    trendChart.setOption({
      title: {
        text: '订单趋势',
        left: 'center',
      },
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: ['订单数量', '销售额'],
        top: 30,
      },
      xAxis: {
        type: 'category',
        data: data.orderTrend.map(item => item.date.substring(5)),
      },
      yAxis: [
        {
          type: 'value',
          name: '订单数量',
          position: 'left',
        },
        {
          type: 'value',
          name: '销售额',
          position: 'right',
        },
      ],
      series: [
        {
          name: '订单数量',
          type: 'line',
          data: data.orderTrend.map(item => item.orders),
          smooth: true,
        },
        {
          name: '销售额',
          type: 'bar',
          yAxisIndex: 1,
          data: data.orderTrend.map(item => item.revenue),
        },
      ],
    });

    // 订单状态分布图
    const statusChart = echarts.init(document.getElementById('status-chart'));
    statusChart.setOption({
      title: {
        text: '订单状态分布',
        left: 'center',
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
      },
      series: [
        {
          name: '订单状态',
          type: 'pie',
          radius: '50%',
          data: data.statusDistribution.map(item => ({
            value: item.count,
            name: getStatusName(item.status),
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    });
  };

  // 获取状态名称
  const getStatusName = (status: string) => {
    const statusNames = {
      pending: '待付款',
      paid: '已付款',
      shipped: '已发货',
      delivered: '已完成',
      cancelled: '已取消',
      refunded: '已退款',
    };
    return statusNames[status as keyof typeof statusNames] || status;
  };

  // 热销商品表格列
  const productColumns = [
    {
      title: '排名',
      key: 'rank',
      width: 60,
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '销量',
      dataIndex: 'sales',
      key: 'sales',
      render: (sales: number) => `${sales} 件`,
    },
    {
      title: '销售额',
      dataIndex: 'revenue',
      key: 'revenue',
      render: (revenue: number) => `¥${revenue.toLocaleString()}`,
    },
  ];

  // 优质客户表格列
  const customerColumns = [
    {
      title: '排名',
      key: 'rank',
      width: 60,
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '客户姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '订单数',
      dataIndex: 'orders',
      key: 'orders',
      render: (orders: number) => `${orders} 单`,
    },
    {
      title: '消费金额',
      dataIndex: 'revenue',
      key: 'revenue',
      render: (revenue: number) => `¥${revenue.toLocaleString()}`,
    },
  ];

  if (!statistics) {
    return <div>加载中...</div>;
  }

  return (
    <div style={{ padding: '24px' }}>
      {/* 筛选条件 */}
      <Card style={{ marginBottom: '24px' }}>
        <Row gutter={16} align="middle">
          <Col>
            <Space>
              <Text>时间范围:</Text>
              <RangePicker
                onChange={(dates) => {
                  if (dates) {
                    setDateRange([dates[0]!.toISOString(), dates[1]!.toISOString()]);
                  } else {
                    setDateRange(null);
                  }
                }}
              />
              <Select defaultValue="all" style={{ width: 120 }}>
                <Option value="all">全部状态</Option>
                <Option value="completed">已完成</Option>
                <Option value="processing">处理中</Option>
              </Select>
              <Button icon={<ReloadOutlined />} onClick={loadStatistics}>
                刷新
              </Button>
              <Button icon={<DownloadOutlined />} type="primary">
                导出报表
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 核心指标 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总订单数"
              value={statistics.totalOrders}
              prefix={<ShoppingCartOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总销售额"
              value={statistics.totalRevenue}
              precision={2}
              prefix="¥"
              valueStyle={{ color: '#f50' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="客户总数"
              value={statistics.totalCustomers}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均订单价值"
              value={statistics.avgOrderValue}
              precision={2}
              prefix="¥"
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 图表区域 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={16}>
          <Card title="订单趋势分析">
            <div id="trend-chart" style={{ height: '400px' }}></div>
          </Card>
        </Col>
        <Col span={8}>
          <Card title="订单状态分布">
            <div id="status-chart" style={{ height: '400px' }}></div>
          </Card>
        </Col>
      </Row>

      {/* 排行榜 */}
      <Row gutter={16}>
        <Col span={12}>
          <Card title="热销商品排行" extra={<Tag color="red">TOP 5</Tag>}>
            <Table
              columns={productColumns}
              dataSource={statistics.topProducts}
              pagination={false}
              size="small"
            />
          </Card>
        </Col>
        <Col span={12}>
          <Card title="优质客户排行" extra={<Tag color="gold">TOP 5</Tag>}>
            <Table
              columns={customerColumns}
              dataSource={statistics.topCustomers}
              pagination={false}
              size="small"
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default OrderStatistics;
